
package ChainNode;
public class ChainWithHeaderNode implements LinearList{

	public ChainNode headerNode;
	public int size;
	
	public  ChainWithHeaderNode(int i) {
		
		headerNode=new ChainNode();
		headerNode.next= headerNode;
		size=0;
	}
	public ChainWithHeaderNode()
	{
		this(60);
	}
	public void checkIndex(int index)
	{
		if(index<0 || index >=size)
		{
			throw new IndexOutOfBoundsException("\n\t indices incorrectos");
		}
	}
	@Override
	public boolean isEmpty() {
		return size==0;
	}

	@Override
	public Object get(int index) {
		checkIndex(index);
		ChainNode aux = headerNode.next;
		for(int i=0;i<index;i++)
			aux=aux.next;
		
		return aux.element;
	}

	@Override
	public int indexOf(Object obj) {
		headerNode.element = obj;
		ChainNode aux= headerNode.next;
		int i=0;
		while(aux!=headerNode && !aux.element.equals(obj))
		{
			aux=aux.next;
			i++;
		}
		if(aux == headerNode)
			return -1;
		return i;
	}

	@Override
	public int size() {
		return size;
	}

	@Override
	public Object remove(int index) {
		Object aux;
		checkIndex(index);
		ChainNode current = headerNode;
		for(int i=0;i<index;i++)
		{
			current= current.next;
		}
		aux= current.next.element;
		current.next= current.next.next;
		size--;
		return aux;
	}

	@Override
	public void add(int index, Object obj) {
		if(index<0 || index>size)
			throw new IndexOutOfBoundsException("\n\t Indices ilegales");
		ChainNode aux = headerNode;
		for(int i=0;i<index;i++)
			aux= aux.next;
		aux.next= new ChainNode(obj,aux.next);
		size++;
		
	}
	public String toString()
	{
		ChainNode aux = headerNode.next;
		StringBuffer s = new StringBuffer("[");
		for(int i=0; i<size; i++)
		{
			if(aux.element==null)
			{
				s.append("null"+ ", ");
			}
			else
			{
				s.append(aux.element + ", ");
			}
			aux=aux.next;
		}
		if(aux!=headerNode.next)
		{
			s.delete(s.length()-2, s.length());
		}
		s.append("]");
		return new String(s);
	}

	
}
